package com.zijidelu.luframework.infrastructure.persistence.repository.core.bizsig;

import com.zijidelu.luframework.base.bizsig.BizSignature;
import com.zijidelu.luframework.base.model.DataModel;
import com.zijidelu.luframework.base.model.PO;
import com.zijidelu.luframework.infrastructure.persistence.repository.core.base.AbstractRepository;
import com.zijidelu.luframework.infrastructure.persistence.repository.core.criteria.BizSigPersistenceContext;
import com.zijidelu.luframework.utils.spring.beans.register.SpringSimpleBeanUtil;
import lombok.Setter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 业务签名数据仓实现类。
 *
 * @author ZIJIDELU
 * @datetime 2025/10/20 17:13
 */
public abstract class AbstractBizSigRepository<P extends PO, D extends DataModel>
        extends AbstractRepository<P, D> implements BizSigRepository<P, D> {

    private final Map<BizSignature<D>, BizSigDataProcessor<P, D>> BIZ_SIG_DATA_PROCESSOR_MAP = new ConcurrentHashMap<>();

    @Setter(onMethod_ = {@Autowired})
    private ObjectProvider<BizSigPersistenceContext<P, D>> bizSigPersistenceContextProvider;
    private BizSigPersistenceContext<P, D> bizSigPersistenceContext;

    @Override
    public BizSigPersistenceContext<P, D> getBizSigPersistenceContext() {
        if (bizSigPersistenceContext == null) {
            bizSigPersistenceContext = bizSigPersistenceContextProvider.getIfAvailable();
        }

        return bizSigPersistenceContext;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public BizSigDataProcessor<P, D> getBizSigDataProcessor(final BizSignature<D> bizSignature) {
        return BIZ_SIG_DATA_PROCESSOR_MAP.computeIfAbsent(bizSignature, key -> {
            BizSigDataProcessor<P, D> bizSigDataProcessor = new BizSigDataProcessorImpl<>(key);
            SpringSimpleBeanUtil.autowire(bizSigDataProcessor);
            return bizSigDataProcessor;
        });
    }

}
